import { ipcMain, BrowserWindow, dialog } from 'electron'
import { writeFile } from 'fs/promises'

/**
 * IPC主进程事件管理类
 * 用于集中注册和处理所有从渲染进程发送到主进程的IPC事件
 */
class IpcMainHandler {
  private isDialogOpen = false

  /**
   * 初始化并注册所有IPC事件监听器
   */
  public initialize(): void {
    this.registerAppControlEvents()
    this.registerRecordEvents()
    this.registerFileOperationEvents()
  }

  /**
   * 注册与应用程序控制相关的事件
   */
  private registerAppControlEvents(): void {
    // 添加窗口控制的处理程序
    ipcMain.on('window-control', (_, command) => {
      const win = BrowserWindow.getFocusedWindow()
      if (!win) return

      switch (command) {
        case 'minimize':
          win.minimize()
          break
        case 'maximize':
          if (win.isMaximized()) {
            win.unmaximize()
            win.webContents.send('window-maximized-change', false)
          } else {
            win.maximize()
            win.webContents.send('window-maximized-change', true)
          }
          break
        case 'close':
          win.close()
          break
      }
    })

    // 处理窗口最大化状态查询
    ipcMain.handle('is-maximized', () => {
      const win = BrowserWindow.getFocusedWindow()
      return win ? win.isMaximized() : false
    })
  }

  /**
   * 注册与文件操作相关的事件
   */
  private registerFileOperationEvents(): void {
    // 选择文件路径
    ipcMain.handle('file:selectDirectory', async () => {
      try {
        const win = BrowserWindow.getFocusedWindow()
        if (!win) {
          throw new Error('无法获取当前窗口')
        }

        // 保存当前窗口状态
        const wasMinimized = win.isMinimized()
        const wasMaximized = win.isMaximized()

        // 禁用窗口交互
        this.isDialogOpen = true
        win.setEnabled(false)

        const result = await dialog.showOpenDialog({
          properties: ['openDirectory']
        })

        // 恢复窗口交互
        win.setEnabled(true)
        this.isDialogOpen = false

        // 恢复窗口状态
        if (wasMinimized) {
          win.minimize()
        } else if (wasMaximized) {
          win.maximize()
        } else {
          win.restore()
        }

        // 确保窗口获得焦点
        win.focus()

        if (!result.canceled && result.filePaths.length > 0) {
          return {
            success: true,
            path: result.filePaths[0]
          }
        } else {
          return {
            success: false,
            error: '用户取消选择'
          }
        }
      } catch (error) {
        // 确保在出错时也恢复窗口交互
        const win = BrowserWindow.getFocusedWindow()
        if (win) {
          win.setEnabled(true)
          win.focus()
        }
        this.isDialogOpen = false
        return {
          success: false,
          error: error instanceof Error ? error.message : '未知错误'
        }
      }
    })
  }

  private registerRecordEvents(): void {
    // 处理保存转换后的视频文件
    ipcMain.handle('record:save-video', async (_, { fileData, filePath }) => {
      try {
        // 将 Buffer 数据写入文件
        await writeFile(filePath, Buffer.from(fileData))
        return { success: true, message: '视频保存成功', filePath }
      } catch (error: any) {
        console.error('保存处理后的视频失败:', error)
        return { success: false, message: `保存视频失败: ${error.message}` }
      }
    })
  }

  /**
   * 移除所有注册的IPC事件监听器
   */
  public removeAllListeners(): void {
    ipcMain.removeAllListeners()
  }
}

// 导出单例实例
export const ipcMainHandler = new IpcMainHandler()
